package com.packenius.library.xspdf;

import java.awt.Color;
import java.util.Map;

/**
 * Holding font data. Only for internal usage!!
 * 
 * @author Christian Packenius, 2013.
 */
class XSFontUsage {
  final XSFontType fontType;

  final double fontSize;

  final double spaceWidth;

  final XSAlignment alignment;

  final Color textFillColor;

  final Color textStrokeColor;

  final XSTextRenderingMode renderMode;

  final XSTextFormattingMode formattingMode;

  XSFontUsage(XSFontType fontType, double fontSize, XSAlignment alignment, Color textFillColor, Color textStrokeColor,
      XSTextRenderingMode renderMode, XSTextFormattingMode formattingMode) {
    this.fontType = fontType;
    this.fontSize = fontSize;
    this.alignment = alignment;
    this.textFillColor = textFillColor;
    this.textStrokeColor = textStrokeColor;
    this.renderMode = renderMode;
    this.formattingMode = formattingMode;
    spaceWidth = getCharacterWidth(' ');
  }

  /**
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals(Object object) {
    if (object == null || !(object instanceof XSFontUsage)) {
      return false;
    }
    XSFontUsage fontUsage = (XSFontUsage) object;
    return fontUsage.fontType.equals(fontType) && fontUsage.fontSize == fontSize && fontUsage.alignment == alignment
        && fontUsage.textFillColor.equals(textFillColor) && fontUsage.textStrokeColor.equals(textStrokeColor)
        && fontUsage.renderMode == renderMode && fontUsage.formattingMode == formattingMode;
  }

  double getTextPartWidth(String part) {
    double width = 0.0;
    for (char ch : part.toCharArray()) {
      width += getCharacterWidth(ch);
    }
    return width;
  }

  private double getCharacterWidth(char code) {
    XST1StdFont fontClass = fontType.fontClass;

    // Character charCode =
    // fontClass.standardEncodingCodeFromUnicodeCharacter.get(code);
    // if (charCode == null) {
    // throw new XSPdfException("Glyph <" +
    // XSUnicodeMapping.getNameFromCode(code) +
    // "> not in standard encoding for code 0x"
    // + Integer.toHexString(code) + " in font " + fontType.fontName + "!");
    // }

    Map<Character, Double> glyphWidths = fontClass.glyphWidths;
    Double glyphWidth = glyphWidths.get(code);
    if (glyphWidth == null) {
      throw new XSPdfException("Glyph <" + XSUnicodeMapping.getNameFromCode(code) + "> with code 0x"
          + Integer.toHexString(code) + " not found in font " + fontType.fontName + "!");
    }
    return glyphWidth * fontSize;
  }
}
